<?php

namespace common\db\behaviors;

use Yii;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;

class MyBehavior extends Behavior {

    public $message = '';
    // 行为的一个属性
    public $property1 = 'This is property in MyBehavior.';

    // 行为的一个方法
    public function method1() {
        return 'Method in MyBehavior is called.';
    }

    // 重载events() 使得在事件触发时，调用行为中的一些方法
    public function events() {
        // 在EVENT_BEFORE_VALIDATE事件触发时，调用成员函数 beforeValidate
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
        ];
    }

    // 注意beforeValidate 是行为的成员函数，而不是绑定的类的成员函数。
    // 还要注意，这个函数的签名，要满足事件handler的要求。
    public function afterInsert(Event $event) {
        $owner = $this->owner;

        Yii::error($owner->attributes);

//        var_dump($owner);
        $owner->on($owner::EVENT_AFTER_PUBLISH, [$owner, 'afterPublish']);
        $owner->trigger($owner::EVENT_AFTER_PUBLISH, new \common\db\AfterPublishEvent([
            'points' => 1,
            'msg' => 2,
        ]));
//        var_dump($event->sender);
        var_dump($event->changedAttributes);
//        debug_print_backtrace();
//        echo $this->message;
        echo '自定义行为里的触发事件,行为里的事件无法传data内容';
    }

    // 注意beforeValidate 是行为的成员函数，而不是绑定的类的成员函数。
    // 还要注意，这个函数的签名，要满足事件handler的要求。
    public function afterUpdate(Event $event) {
//        $this->on(self::EVENT_AFTER_PUBLISH, [$this, 'afterPublish']);
//        $this->trigger(self::EVENT_AFTER_PUBLISH, new \common\db\AfterInsertEvent([
//            'points' => 1,
//            'msg' => 2,
//        ]));
        $owner = $this->owner;
        Yii::error($owner->attributes, __METHOD__);
//        var_dump($owner);
        $owner->on($owner::EVENT_AFTER_PUBLISH, [$owner, 'afterPublish']);
        $owner->trigger($owner::EVENT_AFTER_PUBLISH, new \common\db\AfterPublishEvent([
            'points' => 1,
            'msg' => 2,
        ]));
//        var_dump($event->sender);
        var_dump($event->changedAttributes);
//        debug_print_backtrace();
//        echo $this->message;
        echo '自定义行为里的触发事件,行为里的事件无法传data内容';
    }

    /**
     * Updates a timestamp attribute to the current timestamp.
     *
     * ```php
     * $model->touch('lastVisit');
     * ```
     * @param string $attribute the name of the attribute to update.
     * @throws InvalidCallException if owner is a new record (since version 2.0.6).
     */
    public function touch($attribute) {
        Yii::error($attribute, __METHOD__);
        /* @var $owner BaseActiveRecord */
//        $owner = $this->owner;
//        if ($owner->getIsNewRecord()) {
//            throw new InvalidCallException('Updating the timestamp is not possible on a new record.');
//        }
//        $owner->updateAttributes(array_fill_keys((array) $attribute, $this->getValue(null)));
    }

}
